#include "loop_module/loop.h"
#include "socket_address.h"
#include "socket_channel.h"
#include "socket_connection.h"
#include "tls_socket_connection.h"

#include <cstdint>
#include <cstdio>
#include <gtest/gtest.h>
#include <memory>

TEST(TlsSocket, Init)
{
    Loop                                 loop;
    std::shared_ptr<TlsSocketConnection> connection = std::make_shared<TlsSocketConnection>(&loop);
    connection->OpenSocket();

    std::string                domain   = "www.baidu.com";
    std::string                protocol = "https";

    std::vector<SocketAddress> addr_vec;
    SocketAddress::Address(domain, protocol, addr_vec);
    for (auto & data : addr_vec)
    {
        connection->AsyncConnect(data, [](std::shared_ptr<SocketConnection> con, int result) {
            if (result >= 0)
            {
                printf("connect success.\n");
                std::string content = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\n\r\n";
                con->AsyncRead([](std::shared_ptr<SocketConnection> con, int result, TlsSocketConnection::Message & msg) {
                    printf("on message result : %d.\n", result);
                    if (result >= 0)
                    {
                        printf("%s", std::string((char *)msg.m_data, msg.m_data_length).c_str());
                        msg.m_use_length = msg.m_data_length;
                    }
                });
                con->AsyncWrite((const uint8_t *)content.c_str(), content.size(),
                                [](std::shared_ptr<SocketConnection> c, int result, int size) {
                                    printf("write result %d and size : %d.\n", result, size);
                                });
            }
            else
            {
                printf("connect failed.\n");
            }
        });
        break;
    }
    loop.Run();
}
